package com.useful.mybatis.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.useful.mybatis.handler.FieldFillHandler;
import com.useful.mybatis.handler.IntegerArrayJsonTypeHandler;
import com.useful.mybatis.handler.LongArrayJsonTypeHandler;
import com.useful.mybatis.handler.StringArrayJsonTypeHandler;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * @author : wenchao.long
 * @date : Created in 2021/09/09 16:43 周四
 * @description :
 */
@Configuration
@EnableTransactionManagement
public class MybatisPlusConfig {

    /**
     * 分页插件
     *
     * @return MybatisPlusInterceptor
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    /**
     * 全局注册自定义的TypeHandler
     * 就是对象相互绑定 sql数据库 -> JavaBean
     *
     * @return ConfigurationCustomizer
     */
    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> {
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            typeHandlerRegistry.register(String[].class, StringArrayJsonTypeHandler.class);
            typeHandlerRegistry.register(Long[].class, LongArrayJsonTypeHandler.class);
            typeHandlerRegistry.register(Integer[].class, IntegerArrayJsonTypeHandler.class);
        };
    }

    /**
     * 自动填充数据库创建时间、更新时间
     * 实体类 要继承 BaseEntity
     *
     * @return 全局mybatis配置
     */
    @Bean
    public GlobalConfig globalConfig() {
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setMetaObjectHandler(new FieldFillHandler());
        return globalConfig;
    }
}
